/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core;

import java.io.Serializable;

import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Default implementation of MarkupResolver.
 * 
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: DefaultMarkupResolver.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class DefaultMarkupResolver implements MarkupResolver, Serializable {

	private static final long serialVersionUID = 1L;

	/** Logger */
	private static final Log log = LogFactory.getLog(DefaultMarkupResolver.class);

	/**
	 * {@inheritDoc}
	 * 
	 * <p>
	 * It returns {@link MarkUp#CHTML} for CHTML(iMode) devices,
	 * {@link MarkUp#WML} for WML devices, {@link MarkUp#XHTML_SIMPLE} for whose
	 * devices having simple xhtml support and {@link MarkUp#XHTML_ADVANCED} for
	 * the advanced devices. </p>
	 */
	public MarkUp getMarkupForDevice(Device device) {

		MarkUp markUp = null;

		String xhtmlSupportLevel = "-1";
		String preferredMarkup = "wml_1_1";

		try {
			xhtmlSupportLevel = device
					.getCapability(Constants.CN_XHTML_SUPPORT_LEVEL);
			preferredMarkup = device
					.getCapability(Constants.CN_PREFERRED_MARKUP);

		} catch (CapabilityNotDefinedException e) {

			log.fatal("It is not possible getting markUp from capabilities: "
					+ e.getLocalizedMessage());

			throw new RuntimeException(e.getLocalizedMessage(), e);
		}

		// FIXME Do not operate well
		if (Integer.valueOf(xhtmlSupportLevel).intValue() >= 3) {
			markUp = MarkUp.XHTML_ADVANCED;
		} else if (Integer.valueOf(xhtmlSupportLevel).intValue() >= 1) {
			markUp = MarkUp.XHTML_SIMPLE;
		} else if (preferredMarkup.indexOf("imode") != -1) {
			markUp = MarkUp.CHTML;
		} else {
			markUp = MarkUp.WML;
		}

		if (log.isTraceEnabled()) {
			StrBuilder logBuilder = new StrBuilder();
			logBuilder.append("Device[id: ").append(device.getId())
					.append(", ").append(Constants.CN_XHTML_SUPPORT_LEVEL)
					.append(": ").append(xhtmlSupportLevel).append(", ")
					.append(Constants.CN_PREFERRED_MARKUP).append(": ").append(
							preferredMarkup).append("] returns markup: ")
					.append(markUp);

			log.trace(logBuilder.toString());
		}

		return markUp;

	}

}
